package com.hdcircles.autoform.ui.label.activity;

import android.app.ActivityOptions;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;

import com.cengalabs.flatui.views.FlatEditText;
import com.hdcircles.autoform.R;
import com.hdcircles.autoform.app.Constants;
import com.hdcircles.autoform.base.BaseActivity;
import com.hdcircles.autoform.model.bean.FormBean;
import com.hdcircles.autoform.model.bean.QuestionBean;
import com.hdcircles.autoform.presenter.FormPresenter;
import com.hdcircles.autoform.presenter.contract.FormContract;
import com.hdcircles.autoform.ui.label.adapter.QuestionAdapter;
import com.hdcircles.autoform.util.SharedPreferenceUtil;
import com.hdcircles.autoform.util.SnackbarUtil;

import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;

/**
 * Created by hdcircles on 2016/10/15.
 */

public class FillFormActivity extends BaseActivity<FormPresenter> implements FormContract.View {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.rv_question)
    RecyclerView rvQuestion;
    private FormBean mForm;
    @Inject
    QuestionAdapter adapter;
    private boolean isEmpty;
    private boolean isShared;
    private ProgressDialog dialog;

    private QuestionBean locationQuestion;

    private ImageView ivLocation;

    private ProgressBar locationProgress;

    public static final int MAP_REQUEST_CODE=110;

    private String mAddress;

    private String mAddressName;

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_fill_form;
    }

    @Override
    protected void initEventAndData() {
        Intent intent = getIntent();
        mForm = intent.getParcelableExtra("form");
        isEmpty=intent.getBooleanExtra("isEmpty",true);
        isShared=intent.getBooleanExtra("isShared",false);
        //TODO setToolbar
        String title=null==mForm.getFormName()?"未命名":mForm.getFormName();
        setToolBar(toolbar,title);
        rvQuestion.setLayoutManager(new LinearLayoutManager(this));
        rvQuestion.setAdapter(adapter);
        adapter.setLocationListener(new QuestionAdapter.LocationListener() {
            @Override
            public void getLocation(View itemView) {
                mPresenter.getLocation((FlatEditText) itemView.findViewById(R.id.et_location));
                ivLocation = (ImageView) itemView.findViewById(R.id.iv_location);
                locationProgress= (ProgressBar) itemView.findViewById(R.id.progressBar);
            }
        });
        adapter.setMapListener(new QuestionAdapter.getMapListener() {
            @Override
            public void getMap(QuestionBean questionBean) {
                locationQuestion=questionBean;
                Intent i=new Intent(FillFormActivity.this,MapActivity.class);
                i.putExtra("tableId",mForm.getTableId());
                startActivityForResult(i,MAP_REQUEST_CODE);
            }
        });
        mPresenter.getQuestion(mForm.getId());
        adapter.setChooseListener(new QuestionAdapter.addChooseListener() {
            @Override
            public void getChooseQuestion(QuestionBean questionBean) {
                mPresenter.getChoose(questionBean);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        adapter.notifyDataSetChanged();
                    }
                },3000);
            }
        });

        adapter.setImageListener(new QuestionAdapter.onImageListener() {
            @Override
            public void startUpLoad() {
                showProgress("请稍等");
            }

            @Override
            public void upLoadImage(String path, QuestionBean questionBean) {

                mPresenter.uploadImage(path,questionBean,false);
            }

            @Override
            public void lastImage(String path, QuestionBean questionBean) {
                mPresenter.uploadImage(path,questionBean,true);
            }
        });

        adapter.setToImageViewListener(new QuestionAdapter.jumpToImageViewListener() {
            @Override
            public void onImage(String url,View view) {
                Intent i=new Intent(FillFormActivity.this,ImageActivity.class);
                i.putExtra("imageUrl",url);
                ActivityOptions options=ActivityOptions.makeSceneTransitionAnimation(FillFormActivity.this,view,"shareView");
                startActivity(i,options.toBundle());
            }
        });

    }





    @Override
    public void showQuestion(List<QuestionBean> questionList) {
        adapter.setQuestionBeenList(questionList);
        adapter.notifyDataSetChanged();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.fill_form_menu,menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
                onBackPressedSupport();
                break;
            case R.id.fill_menu_ok:
                if (!mPresenter.validate(adapter.getQuestionBeenList())){
                    showError("必填项不能为空");
                    break;
                }
                showProgress("正在保存");
                FormBean form=new FormBean();
                form.setFormName(mForm.getFormName());
                form.setFormId(mForm.getFormId());
                form.setStatus(Constants.STATUS_DONE);
                form.setQuestion(adapter.getQuestionBeenList());
                if(isEmpty){
                    form.setCreator(mForm.getCreator());
                    form.setWriter(SharedPreferenceUtil.getUserEmail());
                    form.setWriterName(SharedPreferenceUtil.getUserName());
                    form.setTime(System.currentTimeMillis());
                    form.setAddress(mAddress);
                    mPresenter.saveForm(form);
                    //TODO 创建地图数据
                    if (null!=mAddress)
                    mPresenter.createMapData(mForm.getTableId(),mAddressName+"店铺",mAddress);
                    break;
                }
//                if (isShared){
//                    mForm.setStatus(Constants.STATUS_DONE);
//                }
                mPresenter.editFormData(mForm,adapter.getQuestionBeenList());
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void showError(String msg) {
        if (null!=msg)
        SnackbarUtil.showShort(toolbar,msg);
        closeProgress();
        if (null!= ivLocation &&null!=locationProgress){
            ivLocation.setVisibility(View.VISIBLE);
            locationProgress.setVisibility(View.GONE);
        }
    }


    @Override
    public void saveFormSuccess() {
        closeProgress();
        finish();
//        if (isEmpty){
//
//            mPresenter.addInitFormQuantity(mForm.getId(),mForm.getQuantity());
//        }else if (isShared){
////            mPresenter.addInitFormQuantity(mForm.getFormId(),mForm.getQuantity());
//            mPresenter.getInitForm(mForm.getCreator(),mForm.getFormId());
//        }
    }

    @Override
    public void scrollToPosition(int position) {
        rvQuestion.scrollToPosition(position);
    }

    @Override
    public void showLocation(String location,String address, FlatEditText view) {
        mAddress=address;
        view.setText(location);
        ivLocation.setVisibility(View.VISIBLE);
        locationProgress.setVisibility(View.GONE);
    }

    @Override
    public void notifyChange() {

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                adapter.notifyDataSetChanged();
                closeProgress();
            }
        },2000);
    }

    private void showProgress(String msg){
        dialog = new ProgressDialog(this, R.style.AppTheme_Dark_Dialog);
        dialog.setIndeterminate(false);
        dialog.setCancelable(false);
        dialog.setMessage(msg);
        dialog.show();
    }

    private void closeProgress(){
        if (null!=dialog&&dialog.isShowing()){
            dialog.dismiss();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==MAP_REQUEST_CODE&&null!=data){
            String location=data.getStringExtra("location");
            mAddress=location;
            mAddressName=data.getStringExtra("_name");
            locationQuestion.setLocation(location);
            adapter.notifyDataSetChanged();
        }
    }
}
